package common.impl;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ImgScale {
	private BufferedImage bImg; 
	private Integer width;
	private Integer height;
//	private String iname;
//	private String iformat;
	public ImgScale(){		
	}
	public ImgScale(String src){
		try {
			BufferedImage bImg = ImageIO.read(new File(src));//得到BufferedImage对象
			this.bImg = bImg;
			this.width = bImg.getWidth();
			this.height = bImg.getHeight();
//			int ind = src.lastIndexOf(".");
//			int ind1 = src.lastIndexOf("/");
//			this.iformat = src.substring(ind);
//			this.iname = src.substring(ind1+1,ind);			
		} catch (IOException e) {
			System.out.println("Incorret path of Image: "+src);
		}
	}
	
	public void reScaleByHeight(Integer dWidth){
		Integer dHeight = height*dWidth/width;
		Image image = bImg.getScaledInstance(dWidth, dHeight, Image.SCALE_DEFAULT);//通过目标宽高生成目标图象
		BufferedImage bi = new BufferedImage(dWidth, dHeight, BufferedImage.TYPE_INT_RGB);
		Graphics g = bi.getGraphics();
		g.drawImage(image, 0, 0, null);
		g.dispose();
		try {
			ImageIO.write(bi, "jpg", new File("e://result.jpg"));
		} catch (IOException e) {
			e.printStackTrace();
		}		
	}
	
	public static void main(String[] agr0){
		ImgScale is = new ImgScale("e://img.jpg");
		is.reScaleByHeight(800);
	}
}
